import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store';
import { MMessage } from '@/libs';
import { useRoute } from 'vue-router';

export default function useRegister() {
  const route = useRoute();

  const isLoading = ref(false);

  const userStore = useUserStore();
  const router = useRouter();

  async function onRegister({
    username,
    password
  }: {
    username: string;
    password: string;
  }) {
    isLoading.value = true;
    try {
      await userStore.register({
        username,
        password,
        ...route.query
      });

      await userStore.login({
        username,
        password,
        ...route.query,
        loginType: (route.query.reqType || 'username') as
          | 'username'
          | 'QQ'
          | 'WX'
      });

      MMessage({
        content: '注册成功',
        type: 'success'
      });
    } catch (err) {
      console.log(err);
    } finally {
      isLoading.value = false;
    }

    router.push({
      path: '/'
    });
  }

  return {
    onRegister,
    isLoading
  };
}
